"""
此python脚本用于根据t值字段计算显著性字段
显著赋值为1，不显著赋值为0
"""
import arcpy

# 输入要素类路径
fc = r"D:\Lenovo\Desktop\云南大学\毕业设计\毕设工程文件\ArcgisPro\毕设项目\分析结果数据库.gdb\countyzhujiang_MGWR_2020_3"

def add_significance_fields(feature_class,thresholds_dict):
    # 获取所有以'_t'结尾的字段
    t_fields = [f.name for f in arcpy.ListFields(feature_class) if f.name.endswith('_t')]
    
    for t_field in t_fields:
            #检查是否已配置字段阈值
        try:
            if t_field not in thresholds_dict:
                print(f"警告：未找到字段{t_field}的阈值配置")
                continue
            threshold=thresholds_dict[t_field]
            # 生成新字段名
            new_field = t_field.replace("_t", "_显著性")
        
            # 检查字段是否已存在
            if new_field in [f.name for f in arcpy.ListFields(feature_class)]:
                print(f"字段 {new_field} 已存在，跳过处理")
                continue
            
            # 添加短整型字段
            arcpy.AddField_management(
                in_table=feature_class,
                field_name=new_field,
                field_type="SHORT",
                field_alias=new_field
            )
        
            # 构建计算表达式，注意不同年份的自由度不同，T值显著性范围有区别
            # 以95%置信度计算
            expression = f"""
def calc_value(value):
    if value is None:
        return 0  
    return 1 if (abs(value) > {threshold}) else 0
"""
            # 计算字段值
            arcpy.CalculateField_management(
                in_table=feature_class,
                field=new_field,
                expression="calc_value(!{}!)".format(t_field),
                expression_type="PYTHON3",
                code_block=expression
            )
        
            print(f"字段 {new_field} 处理完成，阈值={threshold}")
        
        except Exception as e:
            print(f"处理字段 {t_field} 时出错: {str(e)}")

# t值显著性阈值字典
thresholds_dict={
    '截距_t':2.086,
    'SMCI_2020_t':1.991,
    'GDP_2020_t':2.218,
    '人口_2020_t':2.563,
    '土地利用结构_2020_t':2.365,
    '人口密度_2020_t':2.316,
    '年均温_2020_t':1.996,
    '人均GDP_2020_t':2.455,
    '年降水量_2020_t':2.007,
    '燃烧面积占比_2020_2_t':2.335,
    '火点个数_2020_t':2.523,
    '单位面积FRP_2020_t':2.297
}
# 执行函数
add_significance_fields(fc,thresholds_dict)
